<template>
    <div>
      <!-- 页面头部 -->
      <Header title="分类管理"></Header>
  
      <!-- 操作按钮区域 -->
      <div class="operation-bar">
        <el-button type="success" icon="Plus" @click="openAddDialog">新增分类</el-button>
      </div>
  
      <!-- 搜索栏区域 -->
      <div class="search-bar">
        <el-input :prefix-icon="Search" v-model="searchKeyword" placeholder="根据分类名称搜索" clearable @input="searchCategory" />
      </div>
  
      <!-- 分类列表表格 -->
      <el-table
        :data="paginatedCategories"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#CFCFCFFF', color: '#000000' }"
      >
        <el-table-column prop="id" label="分类ID" />
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column prop="categoryInfo" label="分类描述" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary"  icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger"  icon="Delete" size="small" @click="confirmDeleteCategory(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="totalCategories"
        />
      </div>
  
      <!-- 新增分类弹窗 -->
      <el-dialog v-model="addDialogVisible" title="新增分类">
        <el-form :model="newCategory" label-width="120px">
          <el-form-item label="分类名称">
            <el-input v-model="newCategory.categoryName" />
          </el-form-item>
          <el-form-item label="分类描述">
            <el-input v-model="newCategory.categoryInfo" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveNewCategory">保存</el-button>
            <el-button @click="addDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
  
      <!-- 编辑分类弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑分类">
        <el-form :model="editCategory" label-width="120px">
          <el-form-item label="分类名称">
            <el-input v-model="editCategory.categoryName" />
          </el-form-item>
          <el-form-item label="分类描述">
            <el-input v-model="editCategory.categoryInfo" type="textarea" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEditCategory">保存</el-button>
            <el-button @click="editDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import Header from '@/views/ui/header.vue';
  import { ElMessageBox, ElMessage } from 'element-plus';
  import { getCategoryListApi, getCategoryInfoByIdApi, addCategoryApi, updateCategoryInfoApi, deleteCategoryByIdApi } from '@/apis/CategoryManagerApi';
  import { Calendar, Search } from '@element-plus/icons-vue'
  const categories = ref([]);
  const searchKeyword = ref('');
  const currentPage = ref(1);
  const pageSize = ref(10);
  const totalCategories = ref(0);
  const paginatedCategories = ref([]);
  const addDialogVisible = ref(false);
  const newCategory = reactive({ categoryName: '', categoryInfo: '' });
  const editDialogVisible = ref(false);
  const editCategory = ref({});
  
  const fetchCategoryList = async () => {
    try {
      const res = await getCategoryListApi();
      categories.value = res.data;
      totalCategories.value = categories.value.length;
      applyFiltersAndPagination();
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };
  
  const searchCategory = () => {
    applyFiltersAndPagination();
  };
  
  const applyFiltersAndPagination = () => {
    let filteredCategories = categories.value.filter(category =>
      category.categoryName.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    paginatedCategories.value = filteredCategories.slice(start, end);
  };
  
  const handleSizeChange = size => {
    pageSize.value = size;
    applyFiltersAndPagination();
  };
  
  const handleCurrentChange = page => {
    currentPage.value = page;
    applyFiltersAndPagination();
  };
  
  const openAddDialog = () => {
    newCategory.categoryName = '';
    newCategory.categoryInfo = '';
    addDialogVisible.value = true;
  };
  
  const saveNewCategory = async () => {
    try {
      await addCategoryApi(newCategory);
      ElMessage.success('新增分类成功');
      addDialogVisible.value = false;
      fetchCategoryList();
    } catch (error) {
      ElMessage.error('新增分类失败');
      console.error('新增分类失败:', error);
    }
  };
  
  const openEditDialog = category => {
    editCategory.value = { ...category };
    editDialogVisible.value = true;
  };
  
  const saveEditCategory = async () => {
    try {
      await updateCategoryInfoApi(editCategory.value);
      ElMessage.success('更新分类信息成功');
      editDialogVisible.value = false;
      fetchCategoryList();
    } catch (error) {
      ElMessage.error('更新分类信息失败');
      console.error('更新分类信息失败:', error);
    }
  };
  
  const confirmDeleteCategory = categoryId => {
    ElMessageBox.confirm('确定要删除该分类吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          await deleteCategoryByIdApi(categoryId);
          ElMessage.success('删除分类成功');
          fetchCategoryList();
        } catch (error) {
          ElMessage.error('删除分类失败');
          console.error('删除分类失败:', error);
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
  };
  
  onMounted(() => {
    fetchCategoryList();
  });
  </script>
  
  <style scoped>
  .operation-bar {
    margin-bottom: 10px;
  }
  
  .search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
  }
  
  .pagination {
    margin-top: 10px;
    text-align: right;
  }
  </style>